import { Button, Input, Modal, Space, Table, message } from "antd";
import type { TableProps } from "antd";
import styles from "../../assets/css/MedicalFrontline/PrescriptionManagement.module.css";
import {
  DeleteOutlined,
  FileTextOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import {
  getPreManagementList,
  delPreManagementRow,
  delPreManagementList,
  getPreManagementInfo,
} from "../../api/MedicalFrontline/PrescriptionManagement";
import { useEffect, useState } from "react";

interface DataType {
  id: number;
  name: string;
  age: number;
  address: string;
  tags: string[];
  head: string;
  department: string;
  price: number;
}

interface PrescriptionDataType {
  id: number;
  drugsname: string;
  sort: string;
  type: string;
  img: string;
  other: string;
}

export default function PrescriptionManagement() {
  const [data, setData] = useState<DataType[]>([]);
  const [filteredData, setFilteredData] = useState<DataType[]>([]);
  const [searchName, setSearchName] = useState<string>("");
  const [searchDepartment, setSearchDepartment] = useState<string>("");
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [infoModalData, setInfoModalData] = useState<PrescriptionDataType[]>(
    []
  );
  const [infoModalPrice, setInfoModalPrice] = useState<number>(0);

  const columns: TableProps<DataType>["columns"] = [
    {
      title: "医生头像",
      dataIndex: "head",
      key: "head",
      render: (text) => (
        <img src={text} alt="" style={{ width: "50px", height: "50px" }} />
      ),
    },
    {
      title: "医生姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "处方开具科室",
      dataIndex: "department",
      key: "department",
    },
    {
      title: "处方金额",
      key: "price",
      dataIndex: "price",
    },
    {
      title: "操作",
      key: "action",
      render: (record) => (
        <Space size="middle">
          <a onClick={() => handleViewInfo(record.id)}>
            <FileTextOutlined />
          </a>
          <a onClick={() => handleDelete(record.id)}>
            <DeleteOutlined />
          </a>
        </Space>
      ),
    },
  ];
  const initialization = () => {
    getPreManagementList()
      .then((res) => {
        if (res.code === 1) {
          setData(res.data);
          setFilteredData(res.data);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  useEffect(() => {
    initialization();
  }, []);

  const handleSearch = () => {
    const filteredList = data.filter((item) => {
      return (
        (searchName ? item.name.includes(searchName) : true) &&
        (searchDepartment ? item.department.includes(searchDepartment) : true)
      );
    });
    setFilteredData(filteredList);
  };

  const handleDelete = (rowId: number) => {
    Modal.confirm({
      title: "确定要删除这条记录吗？",
      content: "删除后将无法恢复，请谨慎操作。",
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        delPreManagementRow(rowId)
          .then((res) => {
            if (res.code === 1) {
              message.success("删除成功");
              const newData = data.filter((item) => item.id !== rowId);
              setData(newData);
              setFilteredData(newData);
            } else {
              message.error("删除失败");
            }
          })
          .catch((err) => {
            message.error("删除失败");
          });
      },
      onCancel() {
        console.log("取消删除");
        message.info("取消删除");
      },
    });
  };

  const handleViewInfo = (rowId: number) => {
    getPreManagementInfo(rowId)
      .then((res) => {
        if (res.code === 1 && res.data && res.data[0] && res.data[0].recipel) {
          // 解析处方数据字符串为对象数组
          const recipelString = res.data[0].recipel.replace(/'/g, '"');
          const recipel = JSON.parse(recipelString);
          setInfoModalData(recipel);
          setInfoModalPrice(res.data[0].price);
          setInfoModalVisible(true);
        } else {
          message.error("获取信息失败");
        }
      })
      .catch((err) => {
        message.error("获取信息失败", err);
      });
  };

  const handleDeleteSelected = () => {
    Modal.confirm({
      title: "确定要删除选中的记录吗？",
      content: "删除后将无法恢复，请谨慎操作。",
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        delPreManagementList(JSON.stringify(selectedRowKeys))
          .then((res) => {
            if (res.code === 1) {
              message.success("删除成功");
              return initialization();
            } else {
              message.error("删除失败");
            }
          })
          .catch((err) => {
            message.error("删除失败");
          });
      },
      onCancel() {
        console.log("取消删除");
        message.info("取消删除");
      },
    });
  };

  const rowSelection: TableProps<DataType>["rowSelection"] = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys);
    },
  };

  // 模态框中的表格列配置
  const infoModalColumns = [
    {
      title: "药品图片",
      dataIndex: "img",
      render: (imgUrl: string) => (
        <img
          src={imgUrl}
          alt="药品图片"
          style={{ width: "50px", height: "50px" }}
          onError={(e) => {
            e.target.src =
              "https://tse4-mm.cn.bing.net/th/id/OIP-C.N_jgczL0F1LnUWytCsrQ7QHaHa?rs=1&pid=ImgDetMain";
          }}
        />
      ),
    },
    {
      title: "药品名称",
      dataIndex: "drugsname",
    },
    {
      title: "药品分类",
      dataIndex: "sort",
    },
    {
      title: "药品规格",
      dataIndex: "type",
    },
    {
      title: "药品单价",
      dataIndex: "price",
    },
    {
      title: "药品数量",
      dataIndex: "count",
    },
    {
      title: "药品有效期",
      dataIndex: "endtime",
      render: (text: string) => {
        const date = new Date(text);
        const year = date.getFullYear();
        // 月份从0开始，所以需要加1
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const timeDate = `${year}-${month.toString().padStart(2, "0")}-${day
          .toString()
          .padStart(2, "0")}`;
        return <>{timeDate}</>;
      },
    },
    {
      title: "用药备注",
      dataIndex: "other",
    },
  ];

  const showInfoModal = () => (
    <Modal
      title="处方详细信息"
      open={infoModalVisible}
      onCancel={() => setInfoModalVisible(false)}
      footer={null}
      style={{ minWidth: "1000px" }}
    >
      <Table
        columns={infoModalColumns}
        dataSource={infoModalData}
        pagination={false}
      />
      <div
        style={{
          display: "flex",
          justifyContent: "end",
          alignItems: "flex-end",
          marginTop: "10px",
          fontWeight: "bold",
        }}
      >
        总价：{infoModalPrice}元
      </div>
    </Modal>
  );

  return (
    <div className={styles.bigBox}>
      <div className={styles.head}>
        <div className={styles.left}>
          <div className={styles.doctor}>
            医生名称：
            <Input
              type="text"
              placeholder="请输入医生名称"
              value={searchName}
              onChange={(e) => setSearchName(e.target.value)}
            />
          </div>
          <div className={styles.department}>
            处方开具科室：
            <Input
              type="text"
              placeholder="请输入处方科室"
              value={searchDepartment}
              onChange={(e) => setSearchDepartment(e.target.value)}
            />
          </div>
          <div>
            <Button type="primary" onClick={handleSearch}>
              <SearchOutlined />
              查询
            </Button>
          </div>
        </div>
        <div className={styles.right}>
          <Button
            onClick={() => {
              handleDeleteSelected();
            }}
            danger
          >
            删除选中
          </Button>
        </div>
      </div>
      <div>
        <Table<DataType>
          rowSelection={{ type: "checkbox", ...rowSelection }}
          columns={columns}
          rowKey={(row) => row.id}
          dataSource={filteredData}
        />
      </div>
      {showInfoModal()} {/* 渲染模态框 */}
    </div>
  );
}
